package com.wxxymakers.grademark.interceptor;

import com.wxxymakers.grademark.model.entity.WxUser;
import com.wxxymakers.grademark.service.WxUserService;
import com.wxxymakers.grademark.utils.Const;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @AUTHOR soft
 * @DATE 2019/2/27 14:01
 * @DESCRIBE
 */
@Component
public class CookieInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private WxUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        // 自动登录，从cookie中获取用户信息并保存到session
        WxUser user = (WxUser) request.getSession().getAttribute(Const.CURRENT_USER);
        if (user == null) {
            String username = (String) SecurityUtils.getSubject().getPrincipal();
            if (!StringUtils.isEmpty(username)) {
                user = userService.byUsernameJoin(username);
                request.getSession().setAttribute(Const.CURRENT_USER, user);
            }
        }

        return true;
    }
}
